<template>
  <div class="provider-detail-container" v-loading="loading">
    <no-auth v-if="!loading && !hasViewProviderAuth"></no-auth>
    <template v-if="!loading && hasViewProviderAuth">
      <div class="service-detail-header common-detail-header">
        <div class="service-detail-header-left">
          <div class="engineer-basic-info">
            <div v-if="fieldValue.provider">{{ fieldValue.name }}（{{ fieldValue.provider.name }}）</div>
<!--            <div :class="['service-type', serviceType[fieldValue.providerType]]">{{ fieldValue.providerType && fieldValue.providerType.slice(0,2)}}</div>-->
          </div>
        </div>
        <div class="flex-x">
          <el-button type="plain-third" v-if="buttonAuth['edit']" @click="editEngineer">{{$t('common.base.edit')}}</el-button>
          <el-button type="plain-third" v-if="buttonAuth['delete']" @click="logoutEngineer">{{$t('common.base.logout')}}</el-button>
          <el-button type="plain-third" v-if="buttonAuth['delete'] && tenantType === 1" @click="deleteEngineer">{{$t('common.base.delete')}}</el-button>
        </div>
      </div>
      <!-- start 服务商详情折叠面板 -->
      <BaseTileLayoutTabBar
        v-if="taskLayout == 1"
        :bar-list="taskLayoutTabBarList"
        :now-item="leftActiveTab"
        @changeItem="tabBarChangeItem"
        @openLayoutModal="openBaseLayoutModal"
      ></BaseTileLayoutTabBar>
      <!-- start 工程师详情折叠面板 -->
      <base-collapse
        class="task-detail-main-content detail-main-content"
        :show-collapse="showCollapse"
        :direction.sync="collapseDirection"
        :hidePartCollapse="hidePartCollapse"
      >
        <!--start 工程师信息-->
        <template slot="left">
          <div class="task-detail-main-content-left detail-main-content-left" v-show="collapseDirection !== 'left'">
            <BaseTileLayoutTabBar
              v-if="taskLayout == 2"
              :bar-list="leftTabBarList"
              :now-item="leftActiveTab"
              @openLayoutModal="openBaseLayoutModal"
            />
            <form-view
              v-if="formFields.length && leftActiveTab === 'engineerDetail'"
              :value="fieldValue"
              class="basic-info bbx-cell-form-view" :class="formCellCount > 1 ? 'bbx-cell-form-view-split' : ''" :form-cell-count="formCellCount"
              :fields="formFields"
            >
              <!--所属服务商-->
              <template slot="provider" slot-scope="{ field, value }">
                <div class="form-view-row bbx-form-cell-item">
                  <label>{{ field.displayName }}</label>
                  <div v-if="value" class="form-view-row-content">
                    {{ value.name }}({{ value.code }})
                  </div>
                </div>
              </template>
              <!--工程师姓名-->
              <template slot="name" slot-scope="{ field, value }">
                <div class="form-view-row bbx-form-cell-item">
                  <label>{{ field.displayName }}</label>
                  <div v-if="fieldValue.engineerCode" class="form-view-row-content">
                    {{ value }}（{{ fieldValue.engineerCode }}）
                  </div>
                  <div v-else class="form-view-row-content">
                    {{ value }}
                  </div>
                </div>
              </template>
              <!--授权地址-->
              <template slot="authorizeAddress" slot-scope="{ field, value }">
                <div class="form-view-row bbx-form-item bbx-form-item-view-padding">
                  <label>{{ field.displayName }}</label>
                  <div class="form-view-row-content provider-view-area">
                    <el-table :data="value" :border="true" max-height="250" style="width: 100%">
                      <el-table-column prop="province" :label="`${$t('common.base.province')}/${$t('common.base.municipality')}`" />
                      <el-table-column prop="city" :label="`${$t('common.base.district')}/${$t('common.base.town')}`" />
                      <el-table-column prop="dist" :label="`${$t('common.base.district')}/${$t('common.base.prefecture')}`" />
                    </el-table>
                  </div>
                </div>
              </template>
              <!--授权工单类型-->
              <template slot="authorizeTask" slot-scope="{ field, value }">
                <div class="form-view-row bbx-form-cell-item">
                  <label>{{ field.displayName }}</label>
                  <div v-if="value && value.length" class="form-view-row-content">
                    {{ value.map(item => item && item.name).join(';')}}
                  </div>
                </div>
              </template>
              <!--授权产品目录-->
              <template slot="authorizeProduct" slot-scope="{ field, value }">
                <div class="form-view-row bbx-form-cell-item">
                  <label>{{ field.displayName }}</label>
                  <div v-if="value && value.length" class="form-view-row-content">
                    {{ value.map(item => item && item.name).join(';')}}
                  </div>
                </div>
              </template>
              <!--角色-->
              <template slot="role" slot-scope="{ field, value }">
                <div class="form-view-row bbx-form-cell-item">
                  <label>{{ field.displayName }}</label>
                  <div v-if="value" class="form-view-row-content">
                    {{ value.name }}
                  </div>
                </div>
              </template>
              <!--状态-->
              <template slot="status" slot-scope="{ field, value }">
                <div class="form-view-row bbx-form-cell-item">
                  <label>{{ field.displayName }}</label>
                  <div class="form-view-row-content">
                    <div :class="['service-type', statusType[fieldValue.statusValue]]">{{ fieldValue && fieldValue.statusValue}}</div>
                  </div>
                </div>
              </template>
              <!--授权有效期-->
              <template slot="validTime" slot-scope="{ field, value }">
                <div class="form-view-row bbx-form-cell-item">
                  <label>{{ field.displayName }}</label>
                  <div v-if="value" class="form-view-row-content">
                    {{ value.validTime }} {{$t('common.base.to')}} {{ value.inalidTime }}
                  </div>
                </div>
              </template>
            </form-view>
          </div>
          <div class="collapse-left" v-show="collapseDirection === 'left'">
            {{$t('common.base.engineerMessage')}}
          </div>
        </template>
        <!--end 服务商信息-->
        <!-- start 其他信息 -->
        <template slot="right">
          <div class="task-detail-main-content-right" v-show="collapseDirection !== 'right'">
            <!-- 附加组件筛选 S -->
            <BaseBarV3
              v-if="taskLayout == 2"
              :bar-list="rightTabBarList"
              :now-item="rightActiveTab"
              @changeItem="tabBarChangeItem"
              @upDateBarList="(val) => tabBarUpdateList(val, 'provide', id)"
            />
            <div :class="['task-detail-main-content-right-content', {'task-detail-main-content-right-height': taskLayout == 1}]">
              <engineer-info-record v-if="rightActiveTab === 'dynaminInfo'" ref="dynaminRef" :primary-id="id" :tenant-provider-id="tenantProviderId" :provider-name="fieldValue.providerName" :remark-enable="buttonAuth['remark']" :collapse-direction="collapseDirection"></engineer-info-record>
              <TabQualification v-if="rightActiveTab === 'qualificationManagement' && tenantProviderId" :user-id="id" mode="ENGINEER" />
            </div>
          </div>
          <!--  右侧面板收缩显示的内容  -->
          <template slot="rightExtend">
            <div class="collapse-right">
              {{$t('common.base.dynamicInfo')}}
            </div>
          </template>
        </template>
        <!-- end 其他信息 -->
      </base-collapse>
      <!-- end 服务商详情折叠面板 -->
    </template>

    <!-- 通栏设置 -->
    <biz-layout-modal
      ref="bizLayoutModal"
      :columns="formCellCount"
      :biz-layout-type="taskLayout"
      @changeLayout="changeTaskDetailLayout">
    </biz-layout-modal>
  </div>
</template>

<script>
/* api */
import * as ServiceProviderApi from '@src/api/serviceProviderApi';
/* component */
import noAuth from '@src/modules/calendar/noAuth.vue';
import EngineerInfoRecord from './components/EngineerInfoRecord.vue';
import TabQualification from '@src/modules/dept/user/components/tabpane/tabQualification.vue'
import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue';
import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue'
/* util*/
import { safeNewDate } from '@src/util/time';
import { formatDate } from 'pub-bbx-utils';
import platform from '@src/platform'
import { getRootWindowInitData } from '@src/util/window'
import _ from 'lodash'
import { openAccurateTab } from "@src/util/platform";
import { PageRoutesTypeEnum } from "@model/enum/PageRoutesEnum";
import {  getUserGuideStorageBase, setUserGuideStorageBase } from '@src/util/guideStorage'
import i18n from '@src/locales';
import * as FormUtil from '@src/component/form/util'
/*mixin*/
import multiRowMixin from '@src/modules/serviceProvider/serviceProviderManage/mixin'
export default {
  name: 'service-engineer-detail',
  mixins: [multiRowMixin],
  data() {
    return {
      loading: false,
      hasViewProviderAuth: true,
      serviceType: {
        '正常': 'authorize',
        '已注销': 'resigned'
      },
      statusType: {
        '正常': 'authorize',
        '已离职': 'resigned',
      },
      showCollapse: true,
      collapseDirection: '',
      detailName: 'engineerDetail',
      activeName: 'dynaminInfo',
      formFields: [],
      fieldValue: {},
      tenantProviderId: '',
      buttonAuth: {
        edit: false, // 编辑工程师的权限
        remark: false, // 添加备注和删除备注的权限
      }, // 按钮的权限
      id: '',
    }
  },
  components: {
    noAuth,
    EngineerInfoRecord,
    TabQualification,
    BaseTileLayoutTabBar,
    BaseBarV3,
  },
  computed: {
    isProviderUser() {
      return getRootWindowInitData().isProviderUser || false
    },
    // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return getRootWindowInitData().tenantType;
    },
  },
  async created() {
    try {
      this.id = this.$getUrlObj(window).id || '';
      this.tenantProviderId = this.$getUrlObj(window).tenantProviderId || '';
      this.loading = true;
      await this.getEngineerInfo();
    }catch (e) {
      console.error(e)
    } finally {
      this.loading = false;
    }
  },
  mounted(){
    this.computedQualityGuide()
    this.initBannerForEngineer(); // 初始化工程师左右菜单
  },
  methods: {
    // 获取工程师基本信息
    async getEngineerInfo() {
      try {
        let data = {
          tenantProviderId: this.tenantProviderId, // 服务商id
          id: this.id,
          isProviderUser: this.isProviderUser,
        }
        let res = await ServiceProviderApi.getEngineerDetailInfo(data);
        if(res.success && res.code === 0) {
          let sysData = _.cloneDeep(res?.result?.engineerInfoVO) || {};
          sysData.attribute = sysData.formVOList
          this.formFields = res?.result?.header.filter(item => !['loginPassword', 'confirmPassword', 'engineerCode'].includes(item.fieldName) && item.isHidden !== 1);
          sysData = await FormUtil.initRichTextContent(this.formFields, sysData)
          this.fieldValue = sysData;

          res?.result?.buttonAuth.forEach(item => {
            this.buttonAuth[item.type] = item.visible
          });
          // 处理时间戳
          if(this.fieldValue?.validTime?.inalidTime && this.fieldValue?.validTime?.validTime) {
            this.fieldValue.validTime.inalidTime = formatDate(safeNewDate(this.fieldValue.validTime.inalidTime), 'yyyy-MM-dd') || ''
            this.fieldValue.validTime.validTime = formatDate(safeNewDate(this.fieldValue.validTime.validTime), 'yyyy-MM-dd') || ''
          }
          // 创建时间
          if(this.fieldValue?.createTime) {
            this.fieldValue.createTime = formatDate(safeNewDate(this.fieldValue.createTime), 'yyyy-MM-dd HH:mm:ss') || ''
          }
          // 上岗日期
          if(this.fieldValue?.engineerDate) {
            this.fieldValue.engineerDate = formatDate(safeNewDate(this.fieldValue.engineerDate), 'yyyy-MM-dd') || ''
          }
        }else {
          this.hasViewProviderAuth = false
        }
      }catch (e) {
        console.error(e);
      }
    },
    // 编辑工程师
    editEngineer() {
      this.closeAndOpenTab(PageRoutesTypeEnum.PageServiceEngineerEdit, this.id, `id=${this.id}&tenantProviderId=${this.tenantProviderId}`)
    },
    // 注销工程师
    async logoutEngineer() {
      try {
        await this.$confirm(this.$t('serviceProvider.logoutEngineerAndResetDefaultStatus'), this.$t('serviceProvider.confirmLogoutEngineer'));
        let res = await ServiceProviderApi.unbindUser([this.id]);
        platform.notification({
          type: res.success ? 'success' : 'error',
          title: res.success ? this.$t('common.base.logoutSuccess') : this.$t('common.base.lououtFailed'),
          message: !res.success && res.message
        })
        if(res.success) {
          // 跳转到列表页面
          this.closeAndOpenTab(PageRoutesTypeEnum.PageServiceManage)
        }
      } catch (e) {
        console.error(e);
      }
    },
    // 删除工程师
    async deleteEngineer() {
      try {
        await this.$confirm(this.$t('serviceProvider.confirmDeleteEngineer'), this.$t('common.base.toast'));
        let res = await ServiceProviderApi.deleteEngineer({ userId: this.id });
        platform.notification({
          type: res.success ? 'success' : 'error',
          title: res.success ? this.$t('common.base.deleteSuccess') : this.$t('common.base.deleteFail'),
          message: !res.success && res.message
        })
        if(res.success) {
          // 跳转到列表页面
          this.closeAndOpenTab(PageRoutesTypeEnum.PageServiceManage)
        }
      } catch (e) {
        console.error(e);
      }
    },
    // 跳转页面
    closeAndOpenTab(type, key = '', params = '',) {
      let ids = window.frameElement.dataset.id;
      this.$platform.closeTab(ids);
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type,
        key,
        params,
        fromId,
        reload: true,
      })
    },
    async computedQualityGuide(){
      try{
        let stashObj = await getUserGuideStorageBase()
        if (!stashObj?.['guide_servicePorviderEngineer_qulitytab']?.isComplete) {
            this.$Guide([{
            content: this.$t('qualificationManagement.view.tips5'),
            haveStep: false,
            nowStep: 1,
            id: 'servicePorviderEngineer-tab-qualificationManagement-guide',
            domId:'tab-qualificationManagement',
            apendToBody:true,
          }], 0, '', (e) => {
            return new Promise((resolve, reject) => {
              resolve()
            })
          }).create().then(res_=>{if(res_)setUserGuideStorageBase({userGuideList:[{
            type:'guide_servicePorviderEngineer_qulitytab',
            step:1,
            isComplete:1
          }]})})
        }
      }catch(err){
        console.error(err)
      }
      
    },
    initBannerForEngineer() {
      let leftTabBarList = [
        { position: 'left', tabLabel:i18n.t('common.base.engineerMessage'), tabName: 'engineerDetail', tabShow: true},
      ]
      let rightTabBarList = [
        { position: 'right', tabLabel:i18n.t('common.base.dynamicInfo'), tabName: 'dynaminInfo', tabShow: true, disabled: true}, // 动态信息
        { position: 'right', tabLabel:i18n.t('common.pageTitle.pageQualificationManagementList'), tabName: 'qualificationManagement', tabShow: true}, // 资质
      ]
      this.initBanner(leftTabBarList, rightTabBarList, 'engineer', this.id);
    },
  }
}
</script>

<style lang="scss">
@import "./EngineerDetailView.scss";
</style>
<style lang="scss" scoped>
.bbx-cell-form-view{
  height: calc(100% - 32px);
  overflow-y: auto;
  padding: 16px;
}
.bbx-cell-form-view-split{
  padding: 16px 4px 16px 16px;
}
.service-detail-header-left {
  flex-grow: 1;
  margin-right: 130px;
  .engineer-basic-info {
    height: 24px;
    font-size: 16px;
    font-weight: 500;
    color: #262626;
    line-height: 24px;
    display: flex;
    align-items: center;
  }
  .provider-other-info {
    display: flex;
    margin-top: 14px;
    span {
      margin-right: 200px;
    };
  }
  button {
    margin: 4px 0;
  }
}
.provider-view-area {
  ::v-deep .el-table--border {
    border: 1px solid #ebeef5!important;
  }
}

.service-type {
  width: 52px;
  height: 22px;
  line-height: 22px;
  border-radius: 11px;
  text-align: center;
  font-size: 12px;
  font-weight: 500;
}
.self-employed {
  background: #FFF2E8;
  color: #FF7A45;
  border: 1px solid #FFD8BF;
}
.authorize {
  background: #F6FFED;
  color: #73D13D;
  border: 1px solid #D9F7BE;
}
.resigned {
  background: #FFFFFF;
  color: #8C8C8C;
  border: 1px solid #E8E8E8;
}
::v-deep .el-table--border {
  border: 1px solid #ebeef5!important;
}
</style>